<?php 

class Add_Validate_Setup_Domain_SavePost_Domain extends Ext_Validate_Abstract
{
    protected $_domain;
    
    protected $_messager;
    const EXISTS              = 'domainExists';
    const USED_BY_ANOTHER     = 'usedByAnother';
    const FORMAT_ERROR        = 'formatError';
    protected $_messageTemplates = array(
        self::EXISTS              => "You have already setup the domain.",
        self::USED_BY_ANOTHER     => "The domain '%domain%' is used by another people.",
        self::FORMAT_ERROR        => "The domain '%domain%' format error.",
    );
    
    public function __construct($domain)
    {
        $this->_domain   = $domain;
        $this->_messager = new Ext_Messager($this->_messageTemplates);
    }
    
    public function isValid()
    {
        $validatorChain = new Zend_Validate();
        $validatorChain
            ->addValidator(new Zend_Validate_NotEmpty(), true)
            ;
        
        if(!$validatorChain->isValid($this->_domain)) {
            $this->addTitleMessages('Domain', $validatorChain->getMessages());
            return false;
        }
        
        if(!Ext_Utility_String::isBlogDomain($this->_domain)){
            $this->addTitleMessages('Domain', $this->_messager->createMessage(self::FORMAT_ERROR, array('domain'=>$this->_domain)));
            return false;
        }
        
        $userId = Ext_Auth_Front::getInstance()->getIdentity();
        $userOne = App_Model_DbTable_User::getInstance()->getRowById($userId);
        if($userOne){
            if($userOne['domain'] != ''){
                $this->addTitleMessages('Domain', $this->_messager->createMessage(self::EXISTS, array('domain'=>$this->_domain)));
                return false;
            }
        }
        
        $domainOne = App_Model_DbTable_Domain::getInstance()->getRowByDomain($this->_domain);
        if($domainOne){
            if($domainOne['userId'] > 0){
                if($domainOne['userId'] != $userId){
                     $this->addTitleMessages('Domain', $this->_messager->createMessage(self::USED_BY_ANOTHER, array('domain'=>$this->_domain)));
                     return false;
                }
            }
        }
        
        return true;
    }
}
